package com.minisoft.pingan;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author JueSu
 * @description: TODO
 * @date 2023/12/10 12:23
 */
public class ExportBd {
    public static void main(String[] args) {
        String outputFilePath = "D:\\temp/baodanResult-"+ DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) +".xlsx";
        List<String> columnList = ListUtil.toList("policyNo","productName","totalPremiumDisplay","insuredName","applicantName");

        int fileCount = 1;
        List<List<Object>> rows = new ArrayList<>();
        for (int i = 1;i <= fileCount;i++) {
            Console.log("处理文件："+i+"/"+fileCount);
            // Read JSON data from the input file
            String jsonData = FileUtil.readString(ExportBd.class.getResource("/baodanResult/"+i),"utf-8");

            // Parse JSON data to get rows and column_list
            JSONObject jsonObject = JSON.parseObject(jsonData);
            JSONArray datalist = jsonObject.getJSONArray("datalist");

            for (Object o : datalist) {
                JSONObject obj = (JSONObject) o;
                if (columnList == null) {
//                    columnList = obj.keySet();
                }
                List<Object> row = new ArrayList<>();
                for (String key : columnList) {
                    row.add(obj.get(key));
                }
                rows.add(row);
            }
        }
        // Create Excel writer
        ExcelWriter writer = ExcelUtil.getWriter(outputFilePath);

        // Set the header row
        writer.writeHeadRow(columnList);

        // Write data rows
        writer.write(rows);

        // Close the writer and save the Excel file
        writer.close();

        System.out.println("done");
    }
}
